package com.baosight.risk.service.riaa.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.riaa.RiquAssessService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riaa.RiaaQuesInquiryMapper;
import com.baosight.risk.mapper.riaa.RiquAssessMapper;
import com.baosight.risk.mapper.riaa.RiquInquiryDetailMapper;
import com.baosight.risk.mapper.riri.RiriRiskMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.service.riaa.entity.RiaaQuesInquiry;
import com.baosight.risk.service.riaa.entity.RiquAssess;
import com.baosight.risk.service.riaa.vo.RiquInquiryDetailVO;
import com.baosight.risk.service.riim.impl.RiimRiskImportServiceImpl;
import com.baosight.risk.service.riri.entity.RiriRisk;
import com.baosight.risk.service.riri.impl.RiriRiskServiceImpl;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;

import lombok.extern.slf4j.Slf4j;

/**
 * @author RayWade
 * @create 2019-12-27 16:02
 */
@Service
@Slf4j
public class RiquAssessServiceImpl extends BaseServiceImpl<RiquAssess> implements RiquAssessService {

    @Autowired
    private RiquAssessMapper riquAssessMapper;

    @Autowired
    private RiriRiskMapper riskMapper;

    @Autowired
    private RiquInquiryDetailMapper inquiryDetailMapper;

    @Autowired
    private XtzyCompanyMapper companyMapper;

    @Autowired
    private RiriRiskServiceImpl ririRiskService;

    @Autowired
    private RiimRiskImportServiceImpl riskImportService;
    @Autowired
    private RiaaQuesInquiryMapper riaaQuesInquiryMapper;
    @Override
    public List<RiquAssess> queryList(RiquAssess assess) {
        return riquAssessMapper.queryList(assess);
    }
    public List<RiquAssess> queryListGroupByRiskNo(RiquAssess assess) {
        List<RiquAssess> riquAssessList = riquAssessMapper.queryListGroupByRiskNo(assess);
        List<RiquAssess> riquAssessNewList = new ArrayList<RiquAssess>();
        for (RiquAssess riquAssess:riquAssessList){
            assess.setRiskNo(riquAssess.getRiskNo());
            List<RiquAssess> riquAssessGetOne = riquAssessMapper.queryList(assess);
            Integer quNum =0;
            RiquAssess riquAssessNew  = new RiquAssess();
            if(CollectionUtils.isNotEmpty(riquAssessGetOne)&&riquAssessGetOne.size()>1){

                for (RiquAssess riquAssessNoe:riquAssessGetOne){
                    quNum+=riquAssessNoe.getQuNum();
                }

            }else if(CollectionUtils.isNotEmpty(riquAssessGetOne)){
                quNum+=riquAssess.getQuNum();
            }
            riquAssessNew.setQuNum(quNum);
            riquAssessNew = riquAssessGetOne.get(0);
            riquAssessNewList.add(riquAssessNew);
        }
        return riquAssessNewList;
    }

    /**
     * 新增问卷评估
     *
     * @param quId
     * @return
     */
    @Override
    public Integer insertRiquAssess(String quId) throws Exception {
        List<RiquInquiryDetailVO> detailVOList = inquiryDetailMapper.quesAnalysis(quId);
        RiquAssess assess = new RiquAssess();
        assess.setQuId(quId);
        List<RiquAssess> assessList = riquAssessMapper.queryList(assess);
        if (CollectionUtils.isNotEmpty(assessList)) {
            throw new Exception(detailVOList.get(0).getAcctYear() + "年度的问卷名称【" + detailVOList.get(0).getQuName() + "】的问卷分析已经生成过问卷评估热力图！");
        }
        
        RiaaQuesInquiry quesInquiry = riaaQuesInquiryMapper.selectByPrimaryKey(quId);
        detailVOList.forEach(o ->{
                insertData(o,quesInquiry.getSendCompCode(),quesInquiry.getSendCompName());
        });
        return 1;
    }

    @Override
    public void updateRiquAssess(List<RiquAssess> assessList) {
        assessList.forEach(o ->{
            updateData(o);
        });
    }

    /**
     * 生成自评
     *
     * @param assessList
     */
    @Override
    public void createRisk(List<RiquAssess> assessList) throws Exception {
        // 先对数据进行过滤，RiskNo存在的就不生成自评数据
        List<RiquAssess> list = assessList.stream().filter(o ->
            StringUtils.isEmpty(o.getRiskNo())).collect(Collectors.toList());
        for (RiquAssess assess : list) {
            if (StringUtils.isEmpty(assess.getDeptCode())) {
                log.error("所属单位不能为空，请填写!");
                throw new Exception("所属单位不能为空，请填写!");
            }
            RiriRisk ririRisk = new RiriRisk();
            BeanUtils.copyProperties(assess,ririRisk);
            ririRisk.setStatus("A03");
            ririRisk.setStatusName("已通过");
            ririRisk.setQuarterCurrent(DateUtils.getQuarter(new Date()));
            ririRisk.setAdminFlag("Y");
            ririRiskService.insertRisk(ririRisk);
        }

    }

    /**
     * 生成重点风险
     *
     * @param assessList
     */
    @Override
    public void createRiskImport(List<RiquAssess> assessList) throws Exception {
        for (RiquAssess assess : assessList) {
            if (StringUtils.isEmpty(assess.getRiskNo())) {
                log.error("风险编码不能为空，请填写!");
                throw new Exception("风险名称为【" + assess.getRiskName() + "】的风险编码不能为空，请先生成风险自评!");
            }
            if (StringUtils.isEmpty(assess.getDeptName())) {
                log.error("所属部门不能为空！");
                throw new Exception("风险名称为【" + assess.getRiskName() + "】的所属部门为空！");
            }
            riskImportService.insertImportByRisk(assess);
        }

    }

    private void insertData(RiquInquiryDetailVO detailVO ,String manageCompCode ,String manageCompName){
        RiquAssess assess = new RiquAssess();
        assess = (RiquAssess) com.baosight.risk.common.bean.BeanUtils.initBean(assess);
        assess.setHisRiskId(assess.getId());
        assess.setQuId(detailVO.getQuId());
        assess.setAcctYear(detailVO.getAcctYear());
        assess.setRiskNo(detailVO.getQuesNo());
        assess.setRiskName(detailVO.getQuesName());
        assess.setRiskType(detailVO.getFieldCode());
        assess.setRiskTypeName(detailVO.getFieldName());
        assess.setCreateFlag(detailVO.getCreateFlag());
        assess.setQuNum(detailVO.getSumCount());
        assess.setManageCompCode(manageCompCode);
        assess.setManageCompName(manageCompName);
        if (StringUtils.isNotEmpty(detailVO.getQuesNo())) {
            List<RiriRisk> riskList = riskMapper.queryByYear(detailVO.getQuesNo());
            if(CollectionUtils.isNotEmpty(riskList)){
                RiriRisk ririRisk = riskList.get(0);
                if(ririRisk != null){
                    assess.setDetailType(ririRisk.getDetailType());
                    assess.setDetailTypeName(ririRisk.getDetailTypeName());
                    assess.setRiskType(ririRisk.getRiskType());
                    assess.setRiskTypeName(ririRisk.getRiskTypeName());
                    assess.setRiskProbability(ririRisk.getRiskProbability());
                    assess.setRiskProbabilityName(ririRisk.getRiskProbabilityName());
                    assess.setImpactDegree(ririRisk.getImpactDegree());
                    assess.setImpactDegreeName(ririRisk.getImpactDegreeName());
                    assess.setRiskDesc(ririRisk.getRiskDesc());
                    assess.setDeptCode(ririRisk.getDeptCode());
                    assess.setDeptName(ririRisk.getDeptName());
                    assess.setCompCode(ririRisk.getCompCode());
                    assess.setCompName(ririRisk.getCompName());
                }
            }
        }
        riquAssessMapper.insert(assess);

    }

    private void updateData(RiquAssess assess) {
        if (StringUtils.isNotEmpty(assess.getDeptCode())) {
            XtzyCompany company = companyMapper.getCompanyInfo(assess.getDeptCode());
            //如果是公司，公司和部门是一样的，如果不是公司，找到上级公司
            if ("1".equals(company.getCompType())) {
                assess.setCompCode(assess.getDeptCode());
                assess.setCompName(assess.getDeptName());
            } else {
                company = companyMapper.getCompByCompCode(company.getPathCode());
                assess.setCompCode(company.getCompCode());
                assess.setCompName(company.getCompName());
            }
        }
        update(assess);
    }
}
